const path = require('path');
const http = require('http');
const { get } = require('lodash');
const express = require('express');
const cors = require('cors');
const router = require('./router');
const error = require('./error');
const logger = require('./logger');
const { getConfig } = require('./utils');
const { connect } = require('./socketio');

const app = express();

// 全局异常处理
process.on('unhandledRejection', (reason, p) => {
  logger.log('Unhandled Rejection at: Promise ', p, ' reason: ', reason);
  // application specific logging, throwing an error, or other logic here
});

process.on('uncaughtException', (err) => {
  logger.log('Caught exception: ', err);
});

const server = http.createServer(app);
connect(server);

app.use(cors()); // 跨域

// parse application/x-www-form-urlencoded
app.use(express.urlencoded({ limit: '100mb', extended: false }));

// parse application/json
app.use(express.json({ limit: '100mb' }));

app.use(express.static(path.join(process.cwd(), 'public')));

app.use(router);

app.use(error);

const config = getConfig();
const port = get(config, 'server.port', 9600);

server.listen(port);

logger.log(`Server is running at http://localhost:${port}`);
